#include<iostream>
#include<memory>
#include <string>
#include<cstring>
#include<unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include"Udp_Server.hpp"
#include"Log.hpp"
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        std::cerr<<"usage 3 nums_command-->[.exe][ip][port]"<<std::endl;
        exit(-1);
    }
    std::string s_ip = argv[1];

    uint16_t port = std::stoi(argv[2]);

    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
    {
        LOG(FATAL,"create socket errno!\n");
        exit(SERVER_ERROR);
    }
    struct sockaddr_in src;
    memset(&src,0,sizeof(src));
    src.sin_family = AF_INET;
    src.sin_addr.s_addr = inet_addr(s_ip.c_str());
    src.sin_port  = htons(port);
    //client端口号让OS分配
    while(true)
    {
        std::string line;
        std::cout<<"please input message: ";
        std::getline(std::cin,line);
        socklen_t len  =sizeof(src);
        //send message;
        int n = sendto(sockfd,line.c_str(),line.size(),0,(struct sockaddr*)(&src),len);
        if(n > 0)
        {
            char buf[1024];
            ssize_t msgdata = recvfrom(sockfd,buf,sizeof(buf)-1,0,(struct sockaddr*)(&src),&len);
            if(msgdata > 0)
            {
                buf[msgdata] = '\0';
                InetAddr addr(src);
                std::cout << "[@" << addr.Ip() << ":" << addr.Port() << "]# " << buf << std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }
    ::close(sockfd);
    return 0;
}